<template>
  <div>
    <BasicDrawer
      v-bind="$attrs"
      :showFooter="true"
      @register="register"
      @ok="handleSubmit"
      :okAuth="'m8:machine:remark:edit'"
      width="40%"
    >
      <BasicForm title="编辑加工备注" @register="registerForm" v-bind="$attrs" />
      <template #title>
        <span>编辑加工备注</span>
      </template>
    </BasicDrawer>
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'WorkCalendarModal',
  });
</script>
<script setup lang="ts">
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { defineComponent, ref } from 'vue';
  import { taskRemarkSave } from '/@/api/m8/machine/remark/remark';
  import { useI18n } from '/@/hooks/web/useI18n';

  const emit = defineEmits(['success', 'register']);
  const { showMessage } = useMessage();
  let record = ref<any>();
  const { t } = useI18n('test.testData');

  const inputFormSchemas: FormSchema[] = [
    {
      label: '任务编码',
      field: 'taskCode',
      component: 'Input',
      componentProps: {},
      required: true,
    },
    {
      label: '机床ID',
      field: 'machineId',
      component: 'Input',
      componentProps: {},
      required: true,
    },
    {
      label: '工序编码',
      field: 'operCode',
      component: 'Input',
      componentProps: {},
      required: true,
    },
    {
      label: '备注',
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
        rows: 10,
      },
      colProps: { lg: 24, md: 24 },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [register, { closeDrawer, setDrawerProps }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    record.value = data;
    setFieldsValue(record.value);
    console.log(data);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        id: record.value.id,
        taskCode: data.taskCode,
        machineId: data.machineId,
        operCode: data.operCode,
        remarks: data.remarks,
        ...data,
      };
      const res = await taskRemarkSave(params);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
